import Taro, { Component } from '@tarojs/taro';
import { View, Text, Button, Swiper, SwiperItem, Image, RichText } from '@tarojs/components';
// import Banner from '../../../static/home/banner.png';··
import Consult from '../../../static/goods-detail/icon_Consultation.png';
import TipsModal from '../../../components/tips-modal/index.js';
import './index.scss';
// import {  } from '../../../services/goods';

import { couponDetail, exchangeGoodsDetail, purchaseGood } from '../../../services/goods';
// import Sku from '../../../components/hot-sku/index.js';
import { set as setGlobalData, get as getGlobalData } from '../../../utils/globalData';
import NavigationBar from '../../../components/navigationBar/index';
import { fullImgUrl } from '../../../utils/utils';

export default class Index extends Component {
  config = {
    navigationBarTitleText: '',
  };

  state = {
    exchangeData: null,
    isShowModal: Taro.getStorageSync('setting').is_tip,
    goods: null,
    goodsSku: null,
    hotGoodsId: 0,
    setting: null,
    isShowGoodsInfo: false,
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    originPrice: 0,
    goodsAttr: null,
    purcharseNum: 1,
    typeRanges: [{ name: '快递配送', is_self: 0 }, { name: '门店自提', is_self: 1 }],
    typeRangeIndexs: 0,
  };

  componentWillMount() {
    console.log(this.$router.params);
    let id = '';

    if (this.$router.params.scene) {
      const scene = decodeURIComponent(this.$router.params.scene + '');
      console.log(scene, 'scene');
      let arr = scene.split('=');
      id = arr[1];
    }
    couponDetail({
      sku_id: this.$router.params.sku_id,
    }).then(res => {
      Taro.setNavigationBarTitle({
        title: res.has_goods.goods_name,
      });
      // res.has_goods.details = res.has_goods.details.replace(
      //   /\<img/gi,
      //   '<img style="width: 100% !important" class="rich-img"'
      // );
      // res.has_goods.banner = res.has_goods.banner.split(',');
      // res.has_goods.banner.forEach((item, index) => {
      //   res.has_goods.banner[index] = fullImgUrl(item);
      // });
      this.setState(
        {
          hotGoodsId: res.id,
          goods: res.has_goods,
          goodsAttr: res,
          setting: getGlobalData('setting'),
          goodsSku: [res.has_sku],
          originPrice: res.origin_price
        },
        () => {
          console.log(this.state.goodsSku, 'ssss');
        }
      );
    });
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() { }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  consult = () => {
    let self = this;
    console.log(this.state.setting);
    Taro.showModal({
      title: '咨询热线',
      content: this.state.setting.mobile,
    }).then(res => {
      if (res.confirm) {
        Taro.makePhoneCall({
          phoneNumber: self.state.setting.mobile,
        });
      }
    });
  };
  handleTypes(e) {
    this.setState({
      typeRangeIndexs: e.detail.value
    })
    // setTypeRangeIndex()
  }
  close = () => {
    this.setState({
      isShowModal: false,
    });
  };

  showGoodsInfo() {
    if (!Taro.getStorageSync('token') && !Taro.getStorageSync('userInfo')) {
      Taro.navigateTo({
        url: `/subPackageWork/pages/login/index`
      })
    } else {
      if (this.state.goodsAttr.store_num <= 0) {
      } else {
        console.log(this.state.purcharseNum)
        purchaseGood({
          sku_id: this.$router.params.sku_id,
          num: this.state.purcharseNum,
          is_self:this.state.typeRanges[this.state.typeRangeIndexs].is_self,
          goods_coupon_no:this.$router.params.coupon_no
        }).then(res => {
          // console.log(res)
          // Taro.setStorageSync('deliveryTime', deliveryTime);
          Taro.navigateTo({
            url: `/subPackageWork/pages/settlement/index`
          })
        })
      }
    }
  }

  closeGoodsInfo() {
    console.log('close');
    this.setState({
      isShowGoodsInfo: false,
    });
  }
  opt(type) {
    // 1 add 0 min
    if (type) {
      if (this.state.purcharseNum < this.state.goodsAttr.store_num) {
        this.setState({
          purcharseNum: this.state.purcharseNum + 1
        });
      }
    } else {
      if (this.state.purcharseNum > 1) {
        this.setState({
          purcharseNum: this.state.purcharseNum - 1
        });
        // setPurcharseNum(purcharseNum - 1);
      }
    }
  }

  render() {
    const { isShowModal, goods, isShowGoodsInfo, exchangeData, goodsSku, goodsAttr, purcharseNum } = this.state;
    return (
      <View className='container' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text={goods ? goods.goods_name : '商品详情'} type="bindcard" />
        {isShowModal && goods && !goods.goods_type && <TipsModal onClose={this.close}></TipsModal>}
        {goods && (
          <View className='goods-detail'>
            <View className='top'>
              {/* <Swiper
                className='banner'
                indicatorColor='#DDD'
                indicatorActiveColor='#B2B2B2'
                circular
                indicatorDots
                autoplay
              >
                {goods.banner.map((banner, index) => {
                  return (
                    <SwiperItem key={index}>
                      <Image mode='aspectFit' className='goods-image' src={banner} />
                    </SwiperItem>
                  );
                })}
              </Swiper> */}
              <Image mode='aspectFit' className='goods-image' src={fullImgUrl(goodsAttr.card_cover)} />

              <View class='goods'>
                <View class='goods-info'>
                  <View className='goods-name'>{goods.goods_name}</View>
                  <View className='goods-price'>
                    <Text className='prompt-goods-price'>￥{goods.price}</Text>¥{goodsAttr.price}
                  </View>
                </View>
                <View className='goods-desc'>{goodsAttr.attr_str}</View>
              </View>
            </View>
            <View className='middle'>
              <View className='title'>数量</View>
              {/* <View className="text">数量</View> */}
              {/* 库存{checkedSku.storage}件 */}
              <View className="number"></View>
              <View className="opt-wrapper">
                <View className="opt add" onClick={() => this.opt(0)}>-</View>
                <View className="opt">{purcharseNum}</View>
                <View className="opt min" onClick={() => this.opt(1)}>+</View>
              </View>
            </View>
            <View className='middle'>
              <Picker className="date-picker" range-key="name" range={typeRanges} value={typeRangeIndexs} onChange={this.handleTypes}>
                <View className="wrap">
                  <View className="text">快递类型</View>
                  <View className="number">{typeRanges[typeRangeIndexs].name}</View>
                </View>
              </Picker>
            </View>
            {/* <View className='middle'>
              <View className='title'>商品详情</View>
              <RichText className='rich-text' nodes={goods.details}></RichText>
            </View> */}
          </View>
        )}

          <View className='bottom'>
            <View className='consult-wrapper' onClick={this.consult}>
              <Image src={Consult} className='consult' />
              <View className='text'>咨询</View>
            </View>
            <View className='buy-now' onClick={this.showGoodsInfo}>
              立即购买
            </View>
          </View>
        {/* {isShowGoodsInfo && goods && (
          <Sku
            onClose={this.closeGoodsInfo.bind(this)}
            goodsImage={goods.banner}
            goodsAttr={goods.has_attr}
            goodsSku={goodsSku}
            goodsType={goods.goods_type}
            hotGoodsId={this.state.hotGoodsId}
          />
        )}
        {isShowGoodsInfo && exchangeData && (
          <Sku exchangeData={exchangeData} code={this.$router.params.code} />
        )} */}
      </View>
    );
  }
}
